package com.project.config;


import com.project.BackBoot;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @Author(张阳)
 * @Description(类的描述)rabbitMq配置类
 * @Date(创建时间) 2021/10/13 10:48
 */
@Configuration
public class MQConfig {
    @Autowired
    //注入工厂（已预加载）
    CachingConnectionFactory connectionFactory;
    //必须先注入connectionFactory，再注入rabbitAdmin
    @Autowired
    private RabbitAdmin rabbitAdmin;


    //rabbitMq模板
    @Bean(value = "rabbitTemplate")
    public RabbitTemplate rabbitTemplate() {
        return new RabbitTemplate(connectionFactory);
    }

    @Bean(value = "rabbitAdmin")
    public RabbitAdmin rabbitAdmin() {
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    //创建名叫“queueOne”的队列
    public Queue BackQueue() {
        return new Queue("BackQueue");
    }

    //创建交换机：默认交换机、主题交换机、扇形交换机、头交换机
    //默认交换机
    @Bean
    public DirectExchange directExchange() {
        //给此交换机设置名字
        return new DirectExchange("BackDirectExchange");
    }

    @Bean
    //将队列绑定到默认交换机上
    public Binding queueOneTofanoutExchange() {
        //将queueOne队列绑定到directExchange交换机上         //给此绑定操作设置一个别名，因为mq原则是交换机加
        //连接名，所以用.的形式来取别名
        return BindingBuilder.bind(BackQueue()).to(directExchange()).with("Back.Queue");
    }


    //进行交换机与信道添加，用于添加到远程mq
    @Bean
    public void createExchangeQueue() {
        rabbitAdmin.declareExchange(directExchange());
        //rabbitAdmin.declareExchange(directDeadExchange());
        rabbitAdmin.declareQueue(BackQueue());
        //rabbitAdmin.declareQueue(queueDead());
    }
}
